package com.fnic.pearl.scheduler.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class ResponseUtil {

	private static Logger LOG = Logger.getLogger(ResponseUtil.class);

	private ResponseUtil() {
	}

	public static final String CONTENTTYPE_TEXT = "text/plain;charset=utf-8";

	public static final String CONTENTTYPE_JSON = "application/json;charset=utf-8";

	public static final String CHARENCODING_UTF8 = "UTF-8";

	public static final int HTTP_TIMEOUT = 10000;

	/**
	 * 主动发送http数据
	 * 
	 * @param urlStr
	 * @param msg
	 * @throws Exception
	 */
	public static void sendData(String urlStr, String msg) throws Exception {
		LOG.debug("[**发送数据**] url=" + urlStr + "|data=" + msg);
		HttpURLConnection connection = null;
		URL url = null;
		PrintWriter pw = null;
		InputStream inputStream = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			// connection.setConnectTimeout(0);
			connection.setConnectTimeout(HTTP_TIMEOUT);
			connection.setReadTimeout(HTTP_TIMEOUT);
			connection.addRequestProperty("Content-type", "application/json");
			pw = new PrintWriter(connection.getOutputStream(), true);
			pw.println(msg);
			pw.flush();
			inputStream = connection.getInputStream();
			LOG.debug("[**http status code**] |" + urlStr + "|" + connection.getResponseCode());
		} catch (Exception e) {
			LOG.error("[**请求失败**]url=" + urlStr + "|" + e);
			throw e;
		} finally {
			if (null != pw) {
				pw.close();
				pw = null;
			}
			if (null != inputStream) {
				inputStream.close();
				inputStream = null;
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
	}

	/**
	 * 发送post数据，并获得返回结果
	 * 
	 * @param urlStr
	 * @param msg
	 * @return
	 *
	 */
	public static String sendPostData(String urlStr, String msg) {
		LOG.debug("[**发送数据**] url = " + urlStr + " | data = " + msg);
		HttpURLConnection connection = null;
		URL url = null;
		PrintWriter pw = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		InputStreamReader inputReader = null;
		BufferedReader in = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setConnectTimeout(HTTP_TIMEOUT);
			connection.setReadTimeout(HTTP_TIMEOUT);
			connection.addRequestProperty("Content-type", "application/json");
			outputStream = connection.getOutputStream();
			pw = new PrintWriter(outputStream, true);
			pw.println(msg);
			pw.flush();
			inputStream = connection.getInputStream();
			inputReader = new InputStreamReader(inputStream, "utf-8");
			in = new BufferedReader(inputReader);
			String inputLine;
			String result = "";
			while ((inputLine = in.readLine()) != null) {
				result = result + inputLine;
			}
			LOG.debug("[**http status code**] |" + urlStr + "|" + connection.getResponseCode() + "|返回结果:" + result);
			return result;
		} catch (Exception e) {
			LOG.error(e);
			return StringUtils.EMPTY;
		} finally {
			try {

				if (null != pw) {
					pw.close();
				}
				if (outputStream != null) {
					outputStream.flush();
					outputStream.close();
				}
				if (null != inputStream) {
					inputStream.close();
				}
				if (null != inputReader) {
					inputReader.close();
				}
				if (in != null) {
					in.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (Exception e2) {
				LOG.error(e2);
				return StringUtils.EMPTY;
			}
		}
	}

	/**
	 * 主动发送http数据
	 * 
	 * @param urlStr
	 * @param msg
	 * @throws Exception
	 */
	public static boolean sendData(String urlStr) {
		HttpURLConnection connection = null;
		URL url = null;
		PrintWriter pw = null;
		InputStream inputStream = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);
			connection.setConnectTimeout(HTTP_TIMEOUT);
			connection.setReadTimeout(HTTP_TIMEOUT);
			connection.addRequestProperty("Content-type", "application/json");
			inputStream = connection.getInputStream();
			int httpcode = connection.getResponseCode();
			if (httpcode != HttpServletResponse.SC_OK) {
				LOG.error("[**请求失败**]url=" + urlStr + "|" + httpcode);
				return false;
			}
			LOG.info("[**发送数据**] |" + urlStr + "|" + httpcode);
		} catch (Exception e) {
			LOG.error("[**请求失败**]url=" + urlStr + "|" + e);
			return false;
		} finally {
			if (null != pw) {
				pw.close();
				pw = null;
			}
			if (null != inputStream) {
				inputStream = null;
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return true;
	}

	/**
	 * Description 将字符串内容写入到http相应
	 * 
	 * @param response
	 *            http相应
	 * @param content
	 *            响应内容
	 */
	public static void send(HttpServletResponse response, String content) {

		PrintWriter pw = null;
		response.setCharacterEncoding(CHARENCODING_UTF8);
		response.setContentType(CONTENTTYPE_JSON);
		// response.setContentLength(content.length());

		try {
			pw = response.getWriter();
			pw.println(content);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("response error!");
		} finally {
			if (pw != null) {
				pw.close();
				pw = null;
			}
		}
	}

	public static void main(String[] args) {
		ResponseUtil.sendData("http://www.baidu.com");
	}

}
